import _ from 'lodash';
import processEnvConfig from './processEnv';
import * as Enums from '../utils/Enums';

export interface BusinessServiceConfig {
  ak?: string,
  sk?: string,
  eop?: {
    ak?: string,
    sk?: string,
  },
}

interface ConsoleServiceConfig extends BusinessServiceConfig {
  /**
   * 用于在 staging 环境指定 console 连接的资源池版本
   */
  aimUrl?: string,
}

export interface EnvConfig {
  business?: {
    [serviceType in Enums.ServiceTypes]: BusinessServiceConfig;
  } & {
    [Enums.ServiceTypes.Console]: ConsoleServiceConfig;
  },
  eop?: {
    url: string,
  },
  standalone?: {
    businessServices?: string,
    platformSso?: string,
  },
  cas?: {
    appId?: string,
    appSecret?: string,
    url?: string,
    serviceUrl?: string,
  },
  availableSubApps?: Array<string>,
}

const getEnv = () => process.env.ENV;
const isNodeEnvDevelopment = () => process.env.NODE_ENV === 'development';
const isNodeEnvProduction = () => process.env.NODE_ENV === 'production';
const isEnv3rdPlatform = () => process.env.ENV?.startsWith('ppc-');
const isEnvPublicPlatform = () => !isEnv3rdPlatform();
const isEnvProduction = () => process.env.ENV?.endsWith('production');

const configByEnvType = (await import(`./${process.env.ENV}`)).default as EnvConfig;
const exportConfig = _.merge(configByEnvType, processEnvConfig);
const getBusinessServiceByType = (type?: string) => {
  if (!type) {
    return undefined;
  }
  if (Object.keys(Enums.ServiceTypes).includes(type)) {
    return exportConfig.business[type as Enums.ServiceTypes];
  }
  return undefined;
};

export default {
  ...exportConfig,
  getBusinessServiceByType,
  getEnv,
  isNodeEnvDevelopment,
  isNodeEnvProduction,
  isEnv3rdPlatform,
  isEnvPublicPlatform,
  isEnvProduction,
};
